﻿using EasyXaf.Sample.ODataService.Models;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;
using System.Text.Json;

namespace EasyXaf.Sample.ODataService.Controllers;

public class TianqiController : ODataController
{
    private static async Task<IEnumerable<Tianqi>> GetTianqiAsync(string city)
    {
        var httpClient = new HttpClient();
        var response = await httpClient.GetAsync($"https://v.api.aa1.cn/api/api-tianqi-3/index.php?msg={city}&type=1");
        if (response.IsSuccessStatusCode)
        {
            var json = await response.Content.ReadAsStringAsync();
            var result = JsonSerializer.Deserialize<TianqiResult>(json);
            if (result.code == "1")
            {
                return result.data.Select(t =>
                {
                    t.city = city;
                    return t;
                });
            }
        }
        return Array.Empty<Tianqi>();
    }

    private static bool GetFilterFieldValue(string filter, string filed, out string value)
    {
        value = string.Empty;
        var index = filter.IndexOf(filed);
        if (index > -1)
        {
            var startIndex = filter.IndexOf("'", index) + 1;
            if (startIndex > 0)
            {
                var endIndex = filter.IndexOf("'", startIndex);
                if (endIndex > -1)
                {
                    value = filter[startIndex..endIndex];
                    return true;
                }
            }
        }
        return false;
    }

    private static string GetCity(ODataQueryOptions<Tianqi> options)
    {
        var filter = options.Filter?.RawValue;
        if (!string.IsNullOrWhiteSpace(filter))
        {
            if (GetFilterFieldValue(filter, "city", out var city))
            {
                return city;
            }
            else if (GetFilterFieldValue(filter, "Id", out var key))
            {
                return key.Split('_')[0];
            }
        }
        return "北京";
    }

    public async Task<IEnumerable<Tianqi>> Get(ODataQueryOptions<Tianqi> options)
    {
        var city = GetCity(options);
        var tianqi = (await GetTianqiAsync(city)).AsQueryable();
        return options.ApplyTo(tianqi) as IEnumerable<Tianqi>;
    }
}
